package com.fr.plugin.http;

import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONArray;
import com.fr.plugin.MyDecisionDBAccessProvider;
import com.fr.plugin.dao.MyDao;
import com.fr.plugin.entity.MyEntity;
import com.fr.stable.StringUtils;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ListApi extends BaseHttpHandler {
    @Override
    public RequestMethod getMethod() {
        return null;
    }

    @Override
    public String getPath() {
        return "/list";
    }

    @Override
    public boolean isPublic() {
        return true;
    }

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        DBAccessor dbAccessor = MyDecisionDBAccessProvider.getDbAccessor();
        String userName = httpServletRequest.getParameter("userName");
        List<MyEntity> entityList = dbAccessor.runQueryAction(daoContext -> {
            QueryCondition queryCondition = QueryFactory.create();
            if (StringUtils.isNotBlank(userName)) {
                queryCondition.addRestriction(RestrictionFactory.eq("userName", userName));
            }
            List<MyEntity> myEntityList = daoContext.getDAO(MyDao.class).find(queryCondition);
            return myEntityList;
        });
        JSONArray jsonArray = JSONArray.create(entityList);
        WebUtils.printAsJSON(httpServletResponse, jsonArray);
    }
}
